<?
namespace Api
{
	/** Object class
	 * Controller loader and script param parser
	**/
	
	class	ObjectLoader
	{				
	// DEFAULTS !!
		 const C_MODULE 		= 'm';		// module param		
		 const C_CONTROLLER   	= 'c';		// controller param
		 const C_ACTION 		= 'a';		// action param
		 const C_ADDITION		= 'param';	// additions to param
		
	/** 
     * Loading object by address parameters
	 */
		static public function	Load(array $default=array('site','index','index'))
		{            
            self::SetObjectSession();
            
			$objLoader = new ObjectLoader();			
			$param = $objLoader->ParseParams($default);
			$param = $objLoader->ParseParams($default);
 
            \Api\Config::UnsetConfig($param[self::C_MODULE]);
                        
            \Api\Config::getInstance($param[self::C_MODULE]);  
 
             
		//	print_r( $param );	
			
			$classToCall = $param[self::C_MODULE].'\\controller\\'.$param[self::C_CONTROLLER];
            
			// Check if class exists
			if(! class_exists($classToCall)) throw new \Exception("Can't find object".$classToCall);
            // parsing configure file 
                                      
            \Api\Config::set('param',$param);
            
                          
            $config = \Api\Config::Load($param[self::C_MODULE]); 

            if(array_key_exists('Debug',$config))
            {
                \Api\Config::set('debug',$config['Debug']);
            }
            
            
			$ctrl = new $classToCall( $config);	// call class
            
            $objLoader->LoadAutoHelper( $config, $param, $ctrl); 
                              
            $actionToCall = $param[self::C_ACTION].'Action';	
			
			if(!method_exists($ctrl, $actionToCall))
            {
                throw new \Exception("Can't find action ".$actionToCall." in class ".$classToCall);
            }            
          
             
            self::SetObjectSession($param);            
			
			$ctrl->$actionToCall($param[self::C_ADDITION]);  
            
            $param[self::C_ADDITION]='w';                      
			return $ctrl;
		}
        
    /** Load auto helper if object is configured
     */
        private function LoadAutoHelper($config, $param, &$ctrl)
        {
            if(array_key_exists('AutoHelper', $config))
            {
                foreach($config['AutoHelper'] as $k => $v)
                {                    
                    // Loading private module helpers
                    if(!$v['Shared']) 
                    {
                        $call = $param[self::C_MODULE].'\\Helper\\'.$v['Helper'];
                    }else
                    {
                        $call = 'Global\\Helper\\'.$v['Helper'];
                    }
                   
                    $helper = new $call($config, $ctrl);
                    $helper->SetAction($param[self::C_ACTION], $param[self::C_ADDITION]);
                    $ctrl->SetAutoHelper($helper,$v['Alias'])->__auto();
                }               
            } 
        }

	/** Parsing params from query string		 
	**/
		private function ParseParams(array $default)
		{			
			$param = $_GET;//$_SERVER['QUERY_STRING'];		
			//if( empty($param)) return $param=array(); // default controller						
			//$param = explode('&',$param);
						
			$final_params = array();
			
			if(!array_key_exists(self::C_MODULE, $param) || !array_key_exists(self::C_CONTROLLER, $param)
				)
			{				
				
				$final_params[self::C_MODULE]=$default[0];
				$final_params[self::C_CONTROLLER]=$default[1];
				$final_params[self::C_ACTION]=$default[2];
				
				$param=array();
			}else{				
				$final_params[self::C_MODULE]=$param[self::C_MODULE];
				$final_params[self::C_CONTROLLER]=$param[self::C_CONTROLLER];
				
				$final_params[self::C_ACTION]= array_key_exists(self::C_ACTION, $param)?
					$param[self::C_ACTION]:$default[2];
			}								
			$final_params[self::C_ADDITION]=array();
			
			foreach($param as $k => $v)
			{				
				if($k != self::C_MODULE && $k != self::C_CONTROLLER && $k != self::C_ACTION)
					$final_params[self::C_ADDITION]=explode(',',$k);
			}
									
			return ( $final_params );			
		}
		
		/**	GetBaseURL
		 * @desc: Create base url (without params) from $param
		**/
		static public function GetBaseURL(array $param)
		{
			return '/'.$param[self::C_MODULE].'/'.$param[self::C_CONTROLLER].'/'.$param[self::C_ACTION];
		}
        
        /**
         * Setup object session specialy for ajax messages
         */
        static public function SetObjectSession(array $param=array())
        {
            \Api\Config::set('param',$param);
            \Api\Session::set('OBJECT',$param);             
        }
        
        /**
         * Return object session
         * @return array
         */
        static public function GetObjectSession(){
            return \Api\Session::get('OBJECT');
        }
	}
}
?>